//
//  KyMainViewController.swift
//  KyBase
//
//  Created by fangyukui on 2017/10/16.
//  Copyright © 2017年 fangyukui. All rights reserved.
//

import UIKit
class KyMainViewController: UITabBarController {
    
    lazy var composeBtn:UIButton = { ()->UIButton in
        return UIButton(nomalImg: "tabbar_compose_icon_add_highlighted", hlImg: "tabbar_compose_icon_add_highlighted", nomalbgColor: UIColor.orange, target:self,action:#selector(composedClick))
    }()
    
    fileprivate var timer : Timer?
    
     override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        setupChilrdVc()
        setupComposeBtn()
        
        KyNetworkManager.shared.isUserLogin == true ?  setTimer() : ()
        
        delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(showLoginPage), name: NSNotification.Name(rawValue: KyUserLoginNotification), object: nil)
        
    
        
        
    }
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }


}

//MARK:UITabBarControllerDelegate
extension KyMainViewController:UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let idx = childViewControllers.index(of: viewController)
        if selectedIndex==0 && idx == selectedIndex {
            let nav =  childViewControllers.first as! UINavigationController
            let vc  = nav.childViewControllers.first as! KyHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: .now()+1, execute: {
                vc.refreshCtl.beginRefreshing()
                vc.loadData()
            })
            
            
        }
        

        return !viewController.isMember(of: UIViewController.self) //禁止中间
    }
}


//MARK:Timer
extension KyMainViewController{
    fileprivate func setTimer(){
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(timerChange), userInfo: nil, repeats: true)
    }
}



//MARK:UI
extension KyMainViewController{
    
    ///增加中间按钮
    fileprivate func setupComposeBtn(){
        let w = (tabBar.bounds.width / CGFloat(viewControllers?.count ?? 2))
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        tabBar.addSubview(composeBtn)
        
    }
    
    fileprivate func setupChilrdVc(){
        
//        var  localPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
//        localPath = (localPath as NSString).appendingPathComponent("main.json");
//        let data = try? Data(contentsOf: URL(fileURLWithPath: localPath))
//        KyLog(message: data)
    
        
        guard let path =  Bundle.main.path(forResource: "MainVCSettings.json", ofType: nil) else {
            KyLog(message: "load local data error")
            return;
        }
        do {
            let data  = try Data(contentsOf:URL(fileURLWithPath: path))
            if let json  = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? Array<Dictionary<String,Any>>{
//                KyLog(message: json)
                var vcs = [UIViewController]()
                for item in json {
                    vcs.append(controller(dict: item))
                    
                }
                viewControllers = vcs

            }
        } catch let err  {
            KyLog(message: err)
        }

    }
    
    
    
    fileprivate func controller(dict:[String:Any])->UIViewController{
        guard let className = dict["vcName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let vcType = NSClassFromString(Bundle.main.nameSpace +  ".Ky"  + className) as?  UIViewController.Type,
              let visitorInfo = dict["info"] as? Dictionary<String,Any>
        else {
            return UIViewController()
            
        }
        let vc = vcType.init() as! KyBaseViewController
        vc.visitorInfo = visitorInfo
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: (imageName + "_highlighted"))?.withRenderingMode(.alwaysOriginal)
    
        vc.title = title
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 16)], for: .normal)
        let navVc = KyNavViewController(rootViewController: vc)
        return navVc
       
    }
}

//MARK : action
extension KyMainViewController{
     @objc fileprivate func timerChange(){
        KyNetworkManager.shared.getUnread_count { (count) in
            KyLog(message: count)
            self.tabBar.items?.first?.badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
            
        }
        
    }
    @objc fileprivate func composedClick(){
          KyLog(message: "hello")
    }
    @objc fileprivate  func showLoginPage(){
        let vc = UINavigationController(rootViewController: KyAouthLoginViewController())
        present(vc, animated: true) { 
            
        }
    }
}
